#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#define MSGSZ 128

/*
 * 声明消息结构体
 * */

typedef struct msgbuf {
	long mtype;
	char mtext[MSGSZ];
} message_buf;

int main()
{
	int msqid;
	int msgflg = IPC_CREAT | 0666;
	key_t key;
	message_buf sbuf;
	size_t buf_length;

	/*
	 * 得到这个消息队列的id从“name”为1234，可以创建一个服务
	 * */
	key = 1234;

	(void) fprintf(stderr,"\nmsgget: Calling msgget(%xud,%#o)\n",key,msgflg);

	if ( (msqid = msgget(key,msgflg)) < 0) {
		perror("msgget");
		exit(1);
	}
	else 
		(void) fprintf(stderr,"msgget : msgget success ,id = %d\n",msqid);

	/*
	 * 我们想发送数据类型为1的数据
	 * */
	sbuf.mtype = 1;
	(void) fprintf(stderr,"msgget : msgget success ,id = %d\n",msqid);

	(void) strcpy(sbuf.mtext,"Did you get this?");
		
	(void) fprintf(stderr,"msgget : msgget success ,id = %d\n",msqid);

	buf_length = strlen(sbuf.mtext) + 1;//为什么使用MSGSIZ呢？使用strlen才为数据真正的长度
	
	/*
	 * 发送数据
	 * */
	if (msgsnd(msqid,&sbuf,buf_length,IPC_NOWAIT) < 0) {
		printf("%d, %ld ,%s, %zu\n",msqid, sbuf.mtype, sbuf.mtext, buf_length);
		perror("msgsnd");
		exit(EXIT_FAILURE);
	}
	else
		printf ("Message :[%s] Send\n",sbuf.mtext);

	/*
	 * 发送数据，标志为2
	 * */
	sbuf.mtype = 2;
	(void) strcpy (sbuf.mtext,"No ,this not ") ;
	buf_length = strlen(sbuf.mtext) + 1;
	
	if (msgsnd(msqid,&sbuf,buf_length,IPC_NOWAIT) < 0) {
		printf("%d, %ld ,%s, %zu\n",msqid, sbuf.mtype, sbuf.mtext, buf_length);
		perror("msgsnd");
		exit(EXIT_FAILURE);
	}
	else
		printf ("Message :[%s] Send\n",sbuf.mtext);

	exit(EXIT_SUCCESS);


}


















